<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card class="box-card">
            <!-- 搜索栏 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入内容" v-model='params.query' clearable @clear='getUserList'>
                        <el-button slot="append" icon="el-icon-search" @click='getUserList'></el-button>
                    </el-input>
                </el-col>
                <el-col :span="6">
                    <el-button type="primary" @click='dialogVisible=true'>添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 用户列表 -->
            <el-table :data="userList" stripe border>
                <el-table-column type='index'></el-table-column>
                <el-table-column prop="username" label='姓名'></el-table-column>
                <el-table-column prop="email" label='邮箱'></el-table-column>
                <el-table-column prop="mobile" label='电话'></el-table-column>
                <el-table-column prop="role_name" label='角色'></el-table-column>
                <el-table-column prop="mg_state" label='状态'>
                    <!-- 作用域插槽 -->
                    <template slot-scope="scoped">
                        <el-switch v-model="scoped.row.mg_state" active-color="#13ce66"
                            @change='userChange(scoped.row)'>
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label='操作' width='180px'>
                    <template slot-scope="scoped">
                        <el-button type="primary" icon="el-icon-edit" size='mini' @click='showEditUsers(scoped.row.id)'>
                        </el-button>
                        <el-button type="danger" icon="el-icon-delete" size='mini' @click='removeUser(scoped.row.id)'>
                        </el-button>
                        <!-- 分配角色 -->
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable='false'>
                            <el-button type="warning" icon="el-icon-setting" size='mini' @click='setRoles(scoped.row)'>
                            </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页区域
                @size-change(pagesize改变时触发) 
                @current-change(页码发生改变时触发)
                :current-page(设置当前页码)
                :page-size(设置每页的数据条数)
                :total(设置总页数)  -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="params.pagenum" :page-sizes="[1,2,5]" :page-size="params.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
            <!-- 添加用户的弹框 -->
            <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close='dialogClose'>
                <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="addForm.username" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="addForm.password"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="addForm.email"></el-input>
                    </el-form-item>
                    <el-form-item label="手机" prop="mobile">
                        <el-input v-model="addForm.mobile"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addUsers">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 修改用户的弹框 -->
            <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%" @close='editFormClose'>
                <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="editForm.username" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="editForm.email"></el-input>
                    </el-form-item>
                    <el-form-item label="手机" prop="mobile">
                        <el-input v-model="editForm.mobile"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editUserInfo">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 分配角色的弹框 -->
            <el-dialog title="分配角色" :visible.sync="setDialogVisible" width="50%" @close='setDialogVisibleClose'>
                <div>
                    <p>当前的用户: {{roleInfo.username}}</p>
                    <p>当前的用户: {{roleInfo.role_name}}</p>
                    <p>分配新角色：
                        <el-select v-model="selectRoles" placeholder="请选择">
                            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
                            </el-option>
                        </el-select>
                    </p>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="setDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="setRolesInfo">确 定</el-button>
                </span>
            </el-dialog>
        </el-card>

    </div>
</template>

<script>
    export default {
        data() {
            // 验证邮箱规则
            const checkEmail = (rule, value, cb) => {
                const regEmail = /^\w+@\w+(\.\w+)+$/;
                if (regEmail.test(value)) return cb();
                // 返回一个错误提示
                cb(new Error('请输入合法的邮箱'))
            }
            // 验证手机号码规则
            const checkMobile = (rule, value, cb) => {
                const regMobile = /^1[34578]\d{9}$/;
                if (regMobile.test(value)) return cb();
                // 返回一个错误提示
                cb(new Error('请输入合法的手机号码'))
            }
            return {
                // 获取用户列表参数
                params: {
                    query: '',
                    // 当前的页数
                    pagenum: 1,
                    // 当前每页显示多少条数据
                    pagesize: 2
                },
                userList: [],
                total: 0,
                // 控制添加用户弹框是否显示
                dialogVisible: false,
                // 添加用户的表单数据
                addForm: {
                    username: '',
                    password: '',
                    email: '',
                    mobile: ''
                },
                // 添加表单的验证规则
                addFormRules: {
                    username: [
                        { required: true, message: '请输入登录名称', trigger: 'blur' },
                        { min: 3, max: 10, message: '长度在 3 到 10 个字符之间', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请输入登录密码', trigger: 'blur' },
                        { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
                    ],
                    email: [
                        { required: true, message: '请输入邮箱', trigger: 'blur' },
                        { validator: checkEmail, message: '邮箱格式不正确，请重新输入', trigger: 'blur' }
                    ],
                    mobile: [
                        { required: true, message: '请输入手机号码', trigger: 'blur' },
                        { validator: checkMobile, message: '输入正确的手机号码', trigger: 'blur' }
                    ]
                },
                editDialogVisible: false,
                // 查询到的用户信息参数
                editForm: {},
                // 修改用户信息的验证规则
                editFormRules: {
                    email: [
                        { required: true, message: '请输入邮箱', trigger: 'blur' },
                        {
                            validator: checkEmail,
                            message: '邮箱格式不正确，请重新输入',
                            trigger: 'blur'
                        }
                    ],
                    mobile: [
                        { required: true, message: '请输入手机号码', trigger: 'blur' },
                        {
                            validator: checkMobile,
                            message: '手机号码不正确，请重新输入',
                            trigger: 'blur'
                        }
                    ]
                },
                removeDialogVisible: false,
                // 控制分配角色弹框是否显示
                setDialogVisible: false,
                // 获取被分配角色的信息
                roleInfo: {},
                // 所有角色列表
                roleList: [],
                // 被选中角色的id值
                selectRoles: ''
            }
        },
        created() {
            this.getUserList();
        },
        methods: {
            async getUserList() {
                const { data: res } = await this.$axios.get('users', { params: this.params })
                if (res.meta.status !== 200) return this.$message.error('获取用户列表失败');
                this.userList = res.data.users;
                this.total = res.data.total;

            },
            // 监听 pagesize 改变的事件
            handleSizeChange(newSize) {
                this.params.pagesize = newSize;
                this.getUserList();
            },
            // 监听 页码值 改变的事件
            handleCurrentChange(Current) {
                this.params.pagenum = Current;
                this.getUserList();
            },
            // 监听 switch 开关状态的事件
            async userChange(userInfo) {
                const { data: res } = await this.$axios.put(`users/${ userInfo.id }/state/${ userInfo.mg_state }`)
                // console.log(res);
                if (res.meta.status !== 200) {
                    userInfo.mg_state = !userInfo.mg_state;
                    return this.$message.error('更改用户状态失败');
                }
                this.$message.success('更改用户状态成功')
            },
            // 监听添加用户弹框的关闭事件  重置表单
            dialogClose() {
                this.$refs.addFormRef.resetFields();
            },
            // 添加新用户
            addUsers() {
                this.$refs.addFormRef.validate(async valid => {
                    if (!valid) return;
                    // 发送请求
                    const { data: res } = await this.$axios.post('users', this.addForm);
                    if (res.meta.status !== 201) return this.$message.error('添加用户失败');
                    this.$message.success('添加用户成功');
                })
                // 关闭添加用户弹框
                this.dialogVisible = false;
                // 重新获取用户列表
                this.getUserList();
            },
            async showEditUsers(id) {
                // 根据id 查询用户信息
                const { data: res } = await this.$axios.get('users/' + id);
                if (res.meta.status !== 200) return this.$message.error('查询用户失败');
                this.editForm = res.data;
                this.editDialogVisible = true;
            },
            // 监听修改用户信息弹框的关闭事件  重置表单
            editFormClose() {
                this.$refs.editFormRef.resetFields();
            },
            editUserInfo() {
                // 修改用户信息提交的预验证
                this.$refs.editFormRef.validate(async valid => {
                    if (!valid) return;
                    // 通过验证发起修改用户信息请求
                    const { data: res } = await this.$axios.put('users/' + this.editForm.id, {
                        email: this.editForm.email,
                        mobile: this.editForm.mobile
                    });
                    if (res.meta.status !== 200) return this.$message.error('更新信息失败');
                    this.$message.success('更新信息成功');
                    // 关闭弹框
                    this.editDialogVisible = false;
                    // 重新获取用户列表
                    this.getUserList();
                })
            },
            // 删除用户
            async removeUser(id) {
                const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err);
                // 如果用户确认删除，返回字符串 confirm
                // 如果用户取消删除，返回字符串 cancel
                if (confirmResult !== 'confirm') return this.$message.info('已取消删除');
                const { data: res } = await this.$axios.delete('users/' + id);
                if (res.meta.status !== 200) return this.$message.error('删除用户失败');
                this.$message.success('删除用户成功');
                this.getUserList();
            },
            // 分配角色
            async setRoles(userInfo) {
                this.roleInfo = userInfo;
                // 获取角色列表
                const { data: res } = await this.$axios.get('roles');
                if (res.meta.status !== 200) return this.$message.error('获取角色列表失败');
                this.roleList = res.data;
                this.setDialogVisible = true;
            },
            // 监听分配角色弹框关闭事件 重置选择框
            setDialogVisibleClose() {
                this.selectRoles = '';
                this.roleInfo = {}
            },
            // 点击确定按钮 发送请求
            async setRolesInfo() {
                // 判断用户是否选择需要分配的角色
                if (!this.selectRoles) return this.$message.error('请选择需要分配的角色');
                // 发送请求
                const { data: res } = await this.$axios.put(`users/${ this.roleInfo.id }/role`, { rid: this.selectRoles });
                if (res.meta.status !== 200) return this.$message.error('更新角色失败');
                this.$message.success('更新角色成功');
                this.getUserList();
                this.setDialogVisible = false;
            }
        }
    }
</script>

<style scoped>

</style>